package com.xian.ucenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xian.ucenter.commons.Result;
import com.xian.ucenter.entities.Post;
import com.xian.ucenter.entities.PostTag;
import com.xian.ucenter.entities.Tag;
import com.xian.ucenter.entities.vo.PostVo;
import com.xian.ucenter.mapper.PostMapper;
import com.xian.ucenter.service.PostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xian.ucenter.service.PostTagService;
import com.xian.ucenter.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 文章管理表 服务实现类
 * </p>
 *
 * @author xian
 * @since 2022/07/23 02:59
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private PostTagService postTagService;
    @Transactional
    @Override
    public Result savePostVo(PostVo postVo) {
        Post post = BeanUtil.copyProperties(postVo, Post.class);
        String id = post.getId();
        updateById(post);
        List<String> list = postVo.getList();
        postTagService.removePostTagByPostId(id);
        if (list.size()>0) {
            list.forEach(tagId -> {
                long id1 = tagService.count(new QueryWrapper<Tag>().eq("id", tagId));
                PostTag postTag = new PostTag();
                postTag.setPostId(id);
                if (id1 < 1) {
                    Tag tagName = tagService.getOne(new QueryWrapper<Tag>().eq("tag_name", tagId));
                    if (ObjectUtil.isNull(tagName)) {
                        Tag tag = new Tag();
                        tag.setTagName(tagId);
                        tagService.save(tag);
                        postTag.setTagId(tag.getId());
                    }else {
                        postTag.setTagId(tagName.getId());
                    }
                } else {
                    postTag.setTagId(tagId);
                }
                postTagService.save(postTag);
            });
        }
        return Result.ok();
    }
}
